﻿using NineSeas.Services;
using Orchard;
using Orchard.Localization;
using Orchard.Mvc;
using Orchard.Themes;
using Orchard.ContentManagement;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NineSeas.Models;

namespace NineSeas.Controllers
{
    public class HomeController: Controller
    {
        private readonly IOrchardServices _services;
        private readonly IAuthorService _authorService;
        private readonly IBookService _bookService;
        private Localizer T { get; set; }
        public HomeController(IOrchardServices services, IAuthorService authorService, IBookService bookService)
        {
            this._services = services;
            this._authorService = authorService;
            this._bookService = bookService;
            T = NullLocalizer.Instance;
        }

        [Themed]
        public ActionResult Index()
        {
            var settings = _services.WorkContext.CurrentSite.As<NineSeasSettingsPart>();
            
            var featuredBooks = _services.ContentManager.Query<BookPart, BookPartRecord>()
                .Where(b => b.ContentItemRecord.Id == settings.BookFavourite
                    || b.ContentItemRecord.Id == settings.BookFavouriteWeek
                    || b.ContentItemRecord.Id == settings.BookMostViewed
                    || b.ContentItemRecord.Id == settings.BookMostViewedWeek)
                .List();

            var featuredAuthors = _services.ContentManager.Query<AuthorProfilePart, AuthorProfilePartRecord>()
                .Where(a => a.Id == settings.AuthorFavouriteWeek
                    || a.Id == settings.AuthorNewBookWeek)
                .List();

            var books = _bookService.Search(new ViewModels.BookSearchViewModel(), new PaginationInfo() { 
                PageSize = 20
            });

            _services.WorkContext.Layout.Zones["Featured"].Add(_services.New.Home_Commands(), "0");
            return new ShapeResult(this, _services.New.Home(
                    BookFavourite: featuredBooks.FirstOrDefault(b => b.Id == settings.BookFavourite),
                    BookFavouriteWeek: featuredBooks.FirstOrDefault(b => b.Id == settings.BookFavouriteWeek),
                    BookMostViewed: featuredBooks.FirstOrDefault(b => b.Id == settings.BookMostViewed),
                    BookMostViewedWeek: featuredBooks.FirstOrDefault(b => b.Id == settings.BookMostViewedWeek),
                    AuthorFavouriteWeek: featuredAuthors.FirstOrDefault(a => a.Id == settings.AuthorFavouriteWeek),
                    AuthorNewBookWeek: featuredAuthors.FirstOrDefault(a => a.Id == settings.AuthorNewBookWeek),
                    Books: books
                ));
        }
    }
}